import 'package:common_utils/common_utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_hf/apis/apis.dart';
import 'package:xr_dio/xr_dio.dart';

import '../models/recommend.dart';
import '../models/banner.dart';

class HomeProvider extends ChangeNotifier {
  List<BannerMo> get banners => _banners;

  List<BannerMo> _banners = [];

  set banners(List<BannerMo> p) {
    _banners = p;
    notifyListeners();
  }

  /// 广告列表
  loadBanner() async {
    HttpResponse appResponse = (await XrHttpClient.getInstance().get(Apis.getAdvertList)) as HttpResponse;
    if (appResponse.ok) {
      if (ObjectUtil.isNotEmpty(appResponse.data)) {
        banners = getBanners(appResponse.data);
      }
    } else {
      debugPrint("====" + appResponse.error.toString());
    }
  }

  /// 推荐页数
  int pageIndex = 0;

  List<Recommend> get recommends => _recommends;

  List<Recommend> _recommends = [];

  set recommends(List<Recommend> p) {
    _recommends = p;
    notifyListeners();
  }

  /// 推荐是否有更多, 默认true
  bool _haveRecommendMore = true;

  bool get haveRecommendMore => _haveRecommendMore;

  /// 推荐列表
  loadRecommends() async {
    HttpResponse appResponse = (await XrHttpClient.getInstance()
        .get(Apis.getRecommendList, queryParameters: {'pageIndex': pageIndex})) as HttpResponse;
    if (appResponse.ok) {
      if (ObjectUtil.isNotEmpty(appResponse.data)) {
        _haveRecommendMore = true;
        recommends = getRecommends(appResponse.data);
      } else {
        _haveRecommendMore = false;
      }
    } else {
      debugPrint("====" + appResponse.error.toString());
    }
  }

  /// 刷新推荐
  refreshRecommends() {
    pageIndex = 0;
    recommends.clear();
    _haveRecommendMore = true;
    loadRecommends();
  }

  /// 加载更多
  loadMoreRecommends() {
    if (_haveRecommendMore) {
      ++pageIndex;
      loadRecommends();
    }
  }
}
